<?php

require_once 'Pipes/FileSystem/Model/Finder.php';
require_once 'Pipes/FileSystem/Model/Loader.php';
require_once 'Pipes/Filter.php';
require_once 'PipesImpl/Config.php';
require_once 'PipesImpl/Model/Meta.php';

class PipesCore_Models_Finders_One
{
	private $_meta = null;
	private $_pdo = null;

	public function __construct(PipesImpl_Config $config, PipesImpl_Model_Meta $meta) {
		$this->_pdo = $config->pdo;
		$this->_meta = $meta;
		
		$loader = new Pipes_FileSystem_Model_Loader(
			new Pipes_FileSystem_Model_Finder($config)
		);
		$exploded = explode('_', $meta->getModelName());
		$loader->load(array_pop($exploded));
	}

	public function find($criteria) {
		if (!$criteria instanceof PipesImpl_Filter) {
			$criteriaObj = new Pipes_Filter();
			$idKey = $this->_meta->idColumn()->name;
			$criteriaObj->$idKey->equals($criteria);
			$criteria = $criteriaObj;
		}

		$name = $this->_meta->getName();
		$query = "
			SELECT
				{$name}s.*
			FROM
				{$name}s
			WHERE
				{$criteria->getCondition()}
			LIMIT 1";
		$statement = $this->_pdo->prepare($query);
		$statement->execute($criteria->getSubstitutions());

		$properties = $statement->fetch(PDO::FETCH_ASSOC);
		$statement->closeCursor();
		$modelName = $this->_meta->getModelName();
		return new $modelName($this->_meta, $properties);
	}
}
